package edu.biwu;

import edu.biwu.model.Student;
import lombok.extern.log4j.Log4j2;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.InputStream;
import java.time.LocalDate;

@Log4j2
public class MybatisDemo01 {
    @Test
    public void testFindBySno(){
        InputStream is = MybatisDemo01.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml");

        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        SqlSession sqlSession = sqlSessionFactory.openSession();

        Student student=sqlSession.selectOne("test.findBySno",201215122);

        System.out.println(student);

        sqlSession.close();
    }

    @Test
    public void testFindBySname(){
        InputStream is = MybatisDemo01.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml");

        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        SqlSession sqlSession = sqlSessionFactory.openSession();
        sqlSession.selectList("test.findBySname","%李%").forEach(System.out::println);
    }
    @Test
    public void testInsertStudent(){
        InputStream is = MybatisDemo01.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml");

        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        SqlSession sqlSession = sqlSessionFactory.openSession();


        try {
            Student student = new Student("芷若", "女", LocalDate.parse("1996-10-12"));
            sqlSession.insert("test.insertStudent",student);
            sqlSession.commit();
            log.debug("学生信息:{}",student);
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }
    @Test
    public void testUpdateStudent(){
        InputStream is = MybatisDemo01.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml");

        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        SqlSession sqlSession = sqlSessionFactory.openSession();

        try {
            sqlSession.update("test.updateStudent",new Student("芷若", "女", LocalDate.parse("1995-10-12")));

            sqlSession.commit();
        } catch (Exception e) {

            sqlSession.rollback();
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

}
